package com.sx.manage.reserve.thread.threadpool.classify.schedule;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.sx.manage.reserve.thread.threadpool.classify.Task30;

/**
 * 可延时、可定时线程池
 * @author Administrator
 *
 */
public class ScheduleThreadTest {

	// public static void main(String[] args) {
	// // 声明线程池
	// ExecutorService executor =
	// Executors.newScheduledThreadPool(corePoolSize);
	// // 执行多线程
	// executor.execute(new Task());// 参数为，继承thread或者实现runnable的类
	// // 关闭线程池，防止线程泄露
	// executor.shutdown();
	// }
	///在执行器中周期性执行任务
		public static void main(String[] args){
			ScheduledExecutorService executor= Executors.newScheduledThreadPool(1);
			//System.out.printf("Main: Starting at: %s\n",DateUtil.dateToStr(new Date(), DateUtil.TIMESTAMP_FORMAT));
			Task30 task30=new Task30("task30");
		
			ScheduledFuture<?> result=executor.scheduleAtFixedRate(task30, 1, 2, TimeUnit.SECONDS);
			for(int i=0;i<10;i++){/// getDelay 获取下一次要执行任务的剩余时间
				System.out.printf("Main:Delay:{} %d\n",i,result.getDelay(TimeUnit.MILLISECONDS));
				///
				try{
					TimeUnit.MILLISECONDS.sleep(500);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			System.out.println("关闭线程池");
			executor.shutdown();
			try{
				System.out.println("关闭线程池后在睡5秒");
				TimeUnit.SECONDS.sleep(5);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			System.out.printf("Main:Finished at: %s \n",new Date().toGMTString());
		}
}
